package com.wyl.niupi.framework.util.jdkExt;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 读写properties文件的工具类
 *
 * @author 吴宇亮 on 2019/2/7 0007 14:14
 * @blog https://www.cnblogs.com/hafiz/p/5876243.html
 */
public class _PropertyUtil {
    //properties文件名
    public static final String FRAMEWORK_PROPERTIES = "properties/framework.properties";

    //懒加载，维护着所有的properties文件
    public static final Map<String, Properties> propertiesMap = new HashMap<>();

    //初始化resources下的properties文件，将这些文件放入到缓存中
    static {
        try {
            propertiesMap.put(FRAMEWORK_PROPERTIES, loadInClassPath(FRAMEWORK_PROPERTIES));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从类路径下的Resources文件夹加载properties文件
     *
     * @author 吴宇亮 2018-10-9上午10:01:03
     */
    public static Properties loadInClassPath(String propertyFileName) throws IOException{
        Properties properties = propertiesMap.get(propertyFileName);

        if(null !=  properties){
            return properties;
        }else{
            Properties props = new Properties();
            InputStream in = null;

            //第一种，通过类加载器进行获取properties文件流
            in = _PropertyUtil.class.getClassLoader().getResourceAsStream(propertyFileName);

            //第二种，通过类进行获取properties文件流
            //in = _PropertyUtil.class.getResourceAsStream(propertyFileName);

            props.load(in);
            in.close();

            propertiesMap.put(propertyFileName, props);
            return props;
        }
    }

    /**
     * 获取props下的key
     *
     * @author 吴宇亮 2018-10-9上午10:06:08
     */
    public static String getValueByKey(Properties properties, String key){
        if(null == properties) {
            return "";
        }
        return properties.getProperty(key);
    }

}
